/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="service-manager-container">
        <sf-toolbar ref="toolbar">
            <sf-button-primary
                ref="submit"
                class="creat-button btn-blank white"
                icon-cls="iconfuwuceshi"
                default-disabled
                @click="_addSelectService">
                <lang>部署服务</lang>
            </sf-button-primary>
            <!-- <sf-button
                ref="submit"
                class="creat-button btn-blank"
                icon-cls="iconfuwuceshi"
                :default-disabled="true"
                @click="_serviceTest">
                <lang>服务测试</lang>
            </sf-button> -->
            <sf-button
                ref="submit"
                class="creat-button btn-blank"
                icon-cls="iconrefresh"
                @click="_refresh">
                <lang>刷新</lang>
            </sf-button>
            <sf-searchfield
                v-model="searchParams.keyword"
                class="pull-right"
                placeholder="请输入关键字"
                @clear="onEnterkey"
                @trigger="onEnterkey" />
        </sf-toolbar>
        <div
             class="table-data">
            <web-service-table ref="webTable"
                               @get-total="_getWebTotal" />
        </div>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Ref, Prop } from 'vue-property-decorator';
import webServiceTable from './web_sevice_table.vue';
import urlAdapter from 'src/home/mod_common/url_adapter';
import deployUrlAdapter from 'src/home/mod_common/deploy_url_adapter';

const SERVICE_GET = urlAdapter('streaming');

const STREANUING_JOB = urlAdapter('streaming');

import deployServiceForm from 'src/home/mod_cluster/project_manager/components/label_form/deploy_service_form.vue';
import streamServiceForm from 'src/home/mod_cluster/project_manager/components/label_form/stream_service_form.vue';
import selectServiceForm from 'src/home/mod_cluster/project_manager/components/label_form/select_service_form.vue';

import { SfTable } from '@sxf/sf-vue-component';

const PAGE_COUNT = 14;

interface RepositoryParams {
    createTime: string;
    deleted: number;
    description: string;
    id: number;
    metrics: string;
    name: string;
    projectId: number;
    register: number;
    runId: string;
    s3Address: string;
    sourceType: number;
    updateTime: string;
}

@Component({
    components: {
        webServiceTable,
    }
})
export default class FormalRelease extends Vue {
    @Prop({
        type: Array,
        default: () => []
    })
    modelList!: SafeAny[];

    @Ref() webTable!: SfTable<{}>;
    @Ref() streamTable!: SfTable<{}>;

    serviceActiveIndex = 0;
    searchParams = {
        pageSize: PAGE_COUNT,
        pageNum: 0,
        keyword: '',
        projectId: ''
    };

    get projectId () {
        return this.$route.query.projectId || '';
    }
    mounted (): void {
        this.getWebTotal();
    }

    // 刷新grid
    async getWebTotal () {
        // @ts-ignore
        this.searchParams.projectId = this.projectId;
        const WEB_SERVICE_GET = deployUrlAdapter(`projects/${this.projectId}/services`);
        let jsonData = await this.$ajax.get(WEB_SERVICE_GET, this.searchParams);
        let { success, msg, data } = jsonData;
        this.$unmask();
        if (!success) {
            this.$showErr(msg || _('加载数据失败'));
            return;
        }
        this.serviceTypeList[0].total = data.total;
    }

    // 刷新grid
    async getStreamTotal () {
        // @ts-ignore
        this.searchParams.projectId = this.projectId;
        let jsonData = await this.$ajax.get(`${SERVICE_GET}/${this.projectId}/job`, this.searchParams);
        let { success, msg, data } = jsonData;
        this.$unmask();
        if (!success) {
            this.$showErr(msg || _('加载数据失败'));
            return;
        }
        this.serviceTypeList[1].total = data.total;
    }
    _selectServiceType (index: number) {
        this.serviceActiveIndex = index;
    }
    _getWebTotal (total: number) {
        this.serviceTypeList[0].total = total;
    }
    _getStreamTotal (total: number) {
        this.serviceTypeList[1].total = total;
    }
    _refreshGrid () {
        let params = {
            keyword: this.searchParams.keyword
        };
        if (!this.serviceActiveIndex) {
            this.webTable?.refreshGrid(params);
        } else {
            this.streamTable?.refreshGrid(params);
        }
    }
    _refresh () {
        this._refreshGrid();
    }
    onEnterkey () {
        this._refreshGrid();
    }

    // 选择服务弹窗
    _createSelectServiceFormWin () {
        if (!this.selectServiceFormWin) {
            this.selectServiceFormWin = this.$modal(selectServiceForm, {
                autoDestory: true
            });
        }
        return this.selectServiceFormWin;
    }

    // 部署web服务弹窗
    _createDeployServiceFormWin () {
        if (!this.deployServiceFormWin) {
            this.deployServiceFormWin = this.$modal(deployServiceForm, {
                autoDestory: true
            });
        }
        return this.deployServiceFormWin;
    }

    // 部署stream服务弹窗
    _createStreamServiceFormWin () {
        if (!this.streamServiceFormWin) {
            this.streamServiceFormWin = this.$modal(streamServiceForm, {
                autoDestory: true
            });
        }
        return this.streamServiceFormWin;
    }

    _addSelectService () {
        let vm = this;
        vm._addWebServiceManager();
    }

    // 新增stream部署服务
    async _addStreamServiceManager () {
        let formWin = this._createStreamServiceFormWin();
        formWin.open({
            reset: true,
            title: _('部署Stream Service服务'),
            buttons: [
                { actionName: 'back', text: _('上一步') },
                { actionName: 'submit', text: _('确定') },
                'cancel'
            ],
            data: {
                resourceData: {
                    cpuNum: 1,
                    memorySize: 1
                },
                modelList: this.modelList,
                showModelList: true
            },
            callback: (actionName: string) => {
                if (actionName === 'submit') {
                    if (!formWin.$refs.form.isValid()) {
                        this.$showErr(formWin.$refs.form.getInvalidMsgs());
                        return false;
                    }
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    ajaxParams.projectId = this.projectId;
                    this.ajaxSubmitStreamService(ajaxParams, formWin);
                } else if (actionName === 'back') {
                    formWin.hide();
                } else if (actionName === 'cancel') {
                    formWin.hide();
                    this.selectServiceFormWin.hide();
                }
            }
        });
    }

    // 新增/编辑算法的卡片信息
    async ajaxSubmitStreamService (params: RepositoryParams, formWin: vue, fetch = 'post') {
        formWin.$mask();
        let jsonData = await this.$ajax[fetch](`${STREANUING_JOB}/project/${this.projectId}/job`, params);
        formWin.$unmask();
        let { success, msg } = jsonData;
        if (!success) {
            return this.$showErr(msg || _('部署服务失败'));
        }
        this.$ok(_('部署服务成功'));
        formWin.hide();
        this.selectServiceFormWin.hide();
        this.serviceActiveIndex = 1;
        this._refreshGrid();
    }

    // 新增web部署服务
    _addWebServiceManager () {
        let formWin = this._createDeployServiceFormWin();
        formWin.open({
            reset: true,
            title: _('部署Web Service服务'),
            buttons: [
                { actionName: 'back', text: _('上一步') },
                { actionName: 'submit', text: _('确定') },
                'cancel'
            ],
            data: {
                formData: {
                    readableName: '',
                    description: '',
                    protocol: 1,
                    modelId: '',
                    default: {
                        cpuNum: 1,
                        gpuNum: 0,
                        memorySize: 1,
                        minReplicas: 1,
                        maxReplicas: 1,
                        image: '',
                        modelUri: '',
                        modelName: '',
                        imageName: ''
                    }
                },
                modelList: this.modelList,
                showModelList: true
            },
            callback: (actionName: string) => {
                if (actionName === 'submit') {
                    if (!formWin.$refs.form.isValid()) {
                        this.$showErr(formWin.$refs.form.getInvalidMsgs());
                        return false;
                    }
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    let id = ajaxParams.default.modelId;

                    ajaxParams.default.modelUri = this.modelList.filter(item=>item.modelId === id)[0].s3Address;
                    ajaxParams.default.modelName = this.modelList.filter(item=>item.modelId === id)[0].label;
                    ajaxParams.projectId = this.projectId;

                    // ajaxParams.default.modelId = record.id;
                    this.ajaxSubmitWebService(ajaxParams, formWin);
                } else if (actionName === 'back') {
                    formWin.hide();
                } else if (actionName === 'cancel') {
                    formWin.hide();
                    this.selectServiceFormWin.hide();
                }
            }
        });
    }

    // 新增/编辑算法的卡片信息
    async ajaxSubmitWebService (
        params: RepositoryParams,
        formWin: vue,
        fetch = 'post'
    ) {
        formWin.$mask();
        const SERVICE_ADD = deployUrlAdapter(`projects/${this.projectId}/services`);
        let jsonData = await this.$ajax[fetch](SERVICE_ADD, params);
        formWin.$unmask();
        let { success, msg } = jsonData;
        if (!success) {
            return this.$showErr(msg || _('部署服务失败'));
        }
        this.$ok(_('部署服务成功'));
        formWin.hide();
        this.selectServiceFormWin.hide();
        this.serviceActiveIndex = 0;
        this._refreshGrid();
    }
}
</script>
<style lang="less">
.service-manager-container {
    height: calc(100% - 56px);
    background: #fff;
        border: 1px solid #ddd;
    .sfv-toolbar_inner {
        padding: 8px 6px;
        border: none;
    }
    .white {
        color: #fff;
    }
    .service-type__list {
        display: flex;
        margin-right: 20px;
    }
    .service-type__item {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 124px;
        height: 32px;
        border: 1px solid #ddd;
        border-radius: 2px 0 0 2px;
        color: #343a41;
        cursor: pointer;
        margin-right: 5px;
        &:hover,
        &.active {
            border: 1px solid #204ed9;
            color: #204ed9;
        }
    }
    .table-data {
        height: calc(100% - 48px);
    }
}
</style>
